import { app, BrowserWindow, Menu, ipcMain } from 'electron'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import { exec, execFile } from 'node:child_process'
// import { getInstalledApps } from "get-installed-apps"
import pLimit from 'p-limit';

// import { extractIcon } from 'extract-icon'
const __dirname = path.dirname(fileURLToPath(import.meta.url))


process.env.APP_ROOT = path.join(__dirname, '..')

export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST

let win: BrowserWindow | null

function createWindow() {
  win = new BrowserWindow({
    icon: path.join(process.env.VITE_PUBLIC, 'icon.ico'),
    width: 800,
    height: 600,
    fullscreen: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.mjs'),
    },
  })
  // 打开控制台
  // win.webContents.openDevTools({ mode: 'detach' })
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', (new Date).toLocaleString())
  })
  win.webContents.setZoomFactor(1);
  win.webContents.setVisualZoomLevelLimits(1, 1);
  win.webContents.setZoomFactor(1)

  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL)
  } else {
    win.loadFile(path.join(RENDERER_DIST, 'index.html'))
  }
  // win.loadURL('http://localhost:5600');
  Menu.setApplicationMenu(null);
}
// win-close
ipcMain.handle('win-close', () => {
  if (win) {
    win.close()
  }
})
// 监听子进程
ipcMain.handle('closeLoading', async (event, payload) => {
  console.log('aaaaa', event);
  if (win) {
    win.webContents.send('task-done', payload);
  }
  // 执行你的逻辑
  return '主进程返回数据';
});
// 获取应用列表
ipcMain.handle('get-installed-apps', async () => {
  try {
    const apps = await getInstalledAppsOther()
    return { success: true, data: apps }
  } catch (error: any) {
    return { success: false, error: error.message || error.toString() }
  }
})
// 关闭
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
    win = null
  }
})
// 打开应用
ipcMain.handle('open-installed-app', async (event, appPath) => {
  let appPathStr;
  console.log(event);
  console.log(appPath, 'appPath');

  try {
    appPathStr = typeof appPath === 'string' ? JSON.parse(appPath) : appPath;
  } catch (e) {
    return { success: false, error: 'Invalid JSON' };
  }

  if (!appPathStr || !appPathStr.DisplayIcon || !appPathStr.DisplayIcon.includes('.exe')) {
    return { success: false, error: 'Invalid path' };
  }

  const rawPath = onAppDoubleClick(appPathStr); // 你返回的 .exe 路径
  // 如果没有以引号开头和结尾，则包裹路径
  const needsQuotes = !/^".+"$/.test(rawPath);
  const safePath = needsQuotes ? `"${rawPath.replace(/"/g, '\\"')}"` : rawPath;

  // 使用 Start-Process 执行（注意这里不要再加引号）
  const command = `powershell -NoProfile -Command Start-Process -FilePath '${safePath}' -Verb RunAs`;

  return new Promise((resolve) => {
    exec(command, (error) => {
      if (error) {
        console.error('打开程序失败:', error);
        resolve({ success: false, error: error.message });
      } else {
        resolve({ success: true });
      }
    });
  });
});
function onAppDoubleClick(app: any) {
  // 假设 app.DisplayIcon 是带引号或带参数的字符串，需要先处理一下
  const exePath = extractExePath(app.DisplayIcon || app.UninstallString || '');

  if (!exePath) {
    console.error('无法获取应用可执行文件路径');
    return;
  }

  return exePath
}

// 这个函数提取exe路径，和我上面给你的一样
function extractExePath(raw: any) {
  const match = raw.match(/"?(.*?\.exe)"/i) || raw.match(/(.*?\.exe)/i);
  return match ? match[1] : null;
}

app.on('activate', () => {

  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})
const getInstalledAppsOther = async () => {
  let apps: any = await getInstalledApps();
  // 过滤掉无效的或卸载程序
  apps = apps.filter((item: any) => {
    return item.DisplayIcon &&
      (item.DisplayIcon.includes('.exe') || item.DisplayIcon.includes('.lnk')) &&
      !isUninstallExe(item.DisplayIcon) &&
      item.DisplayName !== '桌面纳管 1.0.0';
  });

  const limit = pLimit(1); // 控制并发数为5（可根据性能调整）

  const tasks = apps.map((appItem: any) =>
    limit(async () => {
      let cleanPath = appItem.DisplayIcon.replace(/^"+|"+$/g, '')   // 去掉两端引号
        .replace(/^\\*"?/, '')     // 去掉开头多余的转义和引号
        .replace(/"?\\*$/, '')     // 去掉末尾多余的转义和引号
        .split(',')[0]             // 去掉逗号及之后的参数
        .trim();
      try {
        const icon = await app.getFileIcon(cleanPath, { size: 'large' });
        appItem.image = icon ? icon.toDataURL() : null;
      } catch (e) {
        appItem.image = null;
      }
      appItem.appName = appItem.DisplayName;
    })
  );

  await Promise.all(tasks);

  return apps;
};
const getInstalledApps = () => {
  return new Promise((resolve, reject) => {
    const powershellCommand = `
      $OutputEncoding = [Console]::OutputEncoding = [Text.UTF8Encoding]::new()
      $paths = @(
        "HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*",
        "HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*",
        "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*"
      )
      $apps = foreach ($path in $paths) {
        Get-ItemProperty $path | Where-Object { $_.DisplayName }
      }
      $apps | ConvertTo-Json -Depth 3
    `;

    execFile(
      "powershell.exe",
      ["-NoProfile", "-Command", powershellCommand],
      { encoding: "utf8", maxBuffer: 1024 * 1024 * 20, },
      (error, stdout, stderr) => {
        if (error) return reject(error);
        if (stderr && stderr.length > 0) return reject(stderr);

        try {
          const apps = JSON.parse(stdout);
          resolve(apps);
        } catch (e) {
          reject(`JSON 解析失败: ${e}`);
        }
      }
    );
  });
};
// 判断路径是不是卸载器
function isUninstallExe(p: string) {
  const lower = p.toLowerCase();
  return lower.includes('uninstall') || lower.includes('uninst');
}



app.whenReady().then(createWindow)
